<?php

namespace App\Repository\Commission;

use App\Models\Orders\OrderMiddModel as model;

use Illuminate\Support\Facades\Cache;
use App\Repository\RoleRepository;
use Illuminate\Support\Facades\DB;
use App\Repository\BaseRepository;
use App\Repository\Product\ProductRepository;
use App\Repository\UploadRepository;
use App\Jobs\Subpackage;
use App\Repository\Orders\OrderCommissionFileRepository;
use App\Libs\PhpOffice\Excel;

class CommissionMiddRepository extends  BaseRepository
{
  private $model;
  private $productModel;
  private $dataModel;
  private $isType;
  public function __construct()
  {
    $this->model = new model;  // 佣金上传的文件
    parent::__construct();
  }
  // 佣金逻辑处理
  public function getAllCommissionData()
  {
    if (empty($id)) {
      return $this->returnMsg(1, '传递参数不能为空');
    }
    $model = new OrderCommissionFileRepository();
    $resMore = $model->getOne(['id' => $id, 'is_run' => 0]);
    // $this->log->info('文件参数:' . $id . '查询结果' . json_encode($resMore));
    if (!($resMore)) {
      return $this->returnMsg(2, '未查询到数据');
    }
    $this->isType = $resMore->type;
    return $this->readLongFile($resMore->upload_rout, $resMore->type, $resMore->shop_id, $id);
  }
  public function readLongFile($path, $type, $shop_id, $id = '', $fiel_name = '')
  {
    $path = public_path($path);
    // var_dump($path);
    // die();
    if (empty($path) || !file_exists($path)) {
      return $this->returnMsg(100, '文件不存在');
    }
    if (empty($type)) {
      return $this->returnMsg(102, '类型不能为空');
    }
    if (empty($shop_id)) {
      return $this->returnMsg(103, '用户id 不存在');
    }
    $model = new Excel();
    $res = [];
    $count = 0;
    $fielCount = 0;
    $count_amount = 0;
    $data = $model->importFile($path, ['orderno', 'iccid', 'amount', 'three_msg'], function ($data) use ($shop_id, $id, $fiel_name) {
      $data['shop_id'] = $shop_id;
      $data['more_file_id'] = $id;
      $data['dist_name'] = $fiel_name;
      return $data;
    });
    // var_dump($data);
    if (!empty($data['data'])) {
      foreach (array_chunk($data['data'], 100, true) as $key => $v) {
        $res = $this->oneInsert($v);
      }
      $count = count($data['data']);
    }
    $update = [
      'is_run' => 1,
      'success_num' => $count,
      'fail_num' => $fielCount,
      'count_amount' => $count_amount,
    ];
    $model = new OrderCommissionFileRepository();
    return $model->edit(['id' => $id], $update);
  }
}
